package com.jprocms.module.cms.controller.portal.page;

import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.module.system.api.notice.NoticeApi;
import com.jpro.module.system.api.notice.dto.NoticeRespDTO;
import com.jprocms.module.cms.dal.dataobject.content.TagDO;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.enums.ErrorCodePortalConstants;
import com.jprocms.module.cms.exception.PortalServiceExceptionUtil;
import com.jprocms.module.cms.service.content.ContentCountService;
import com.jprocms.module.cms.service.content.TagService;
import com.jprocms.module.cms.service.site.SiteService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 通知公告跳转页面 Controller
 *
 * @author jprocms
 */
@Controller("noticePageController")
public class NoticePageController {

    private static final String NOTICE_LIST = "sys/notice_list";

    private static final String NOTICE_DETAIL = "sys/notice_detail";


    private final SiteService siteService;
    private final NoticeApi service;
    private final ContentCountService contentCountService;

    public NoticePageController(SiteService siteService, NoticeApi noticeApi, ContentCountService contentCountService) {
        this.siteService = siteService;
        this.service = noticeApi;
        this.contentCountService = contentCountService;
    }

    @GetMapping({"/notice", "/{sitePath:[\\w-]+}/notice"})
    public String index(@PathVariable(required = false) String sitePath, HttpServletRequest request) {
        SiteDO site = siteService.getSite(sitePath);
        contentCountService.viewIndex(site.getId());
        return site.joinTemplate(NOTICE_LIST);
    }

    @GetMapping({"/notice/{id}", "/{sitePath:[\\w-]+}/notice/{id}"})
    public String noticeDetail(@PathVariable(required = false) String sitePath, @PathVariable Long id,
                               HttpServletRequest request, Map<String, Object> modelMap) {
        SiteDO site = siteService.getSite(sitePath);
        final CommonResult<NoticeRespDTO> noticeResult = service.getNotice(id);
        if(noticeResult.isError()){
            throw PortalServiceExceptionUtil.exception(ErrorCodePortalConstants.COMMON_RPC_SYSTEM_ERROR);
        }
        final NoticeRespDTO notice = noticeResult.getData();
        if (notice == null) {
            throw PortalServiceExceptionUtil.exception(ErrorCodePortalConstants.DATA_NOT_EXIST);
        }
        modelMap.put("notice", notice);
        contentCountService.viewIndex(site.getId());
        return site.joinTemplate(NOTICE_DETAIL);
    }

}
